﻿using System;
using System.Data;
using System.Diagnostics;

namespace HQS.TokenInterpolation
{
    /// <summary>
    ///     This class is created to facilitate replacing it with a different implementation.
    /// </summary>
    internal class MathParser
    {
        private static readonly DataTable dataTable = new DataTable();

        public static ParserResult<double?> Parse(string expression)
        {
            ParserResult<double?> result = null;
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            Stopwatch processingWatch = Stopwatch.StartNew();
            try
            {
                object computeResult = dataTable.Compute(expression, null);
                double doubleValue;
                string errorMessage = null;
                if (double.TryParse(Convert.ToString(computeResult), out doubleValue) == false)
                {
                    errorMessage = string.Format("The following expression \"{0}\" didn't evaluate right.", expression);
                }

                result = new ParserResult<double?>(doubleValue);
                if (string.IsNullOrWhiteSpace(errorMessage) == false)
                {
                    result.AddErrorMessage(errorMessage);
                }
            }
            catch (Exception e)
            {
                result = new ParserResult<double?>(null);
                result.AddErrorMessage(e.Message);
            }
            finally
            {
                processingWatch.Stop();
            }

            return result;
        }
    }
}